package agriculture.common.security.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;

import agriculture.system.api.domain.SysUser;
import agriculture.system.api.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Component;
import agriculture.common.core.constant.CacheConstants;
import agriculture.common.core.constant.SecurityConstants;
import agriculture.common.core.utils.JwtUtils;
import agriculture.common.core.utils.ServletUtils;
import agriculture.common.core.utils.StringUtils;
import agriculture.common.core.utils.ip.IpUtils;
import agriculture.common.core.utils.uuid.IdUtils;
import agriculture.common.redis.service.RedisService;
import agriculture.common.security.utils.SecurityUtils;
import agriculture.system.api.model.LoginUser;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    @Autowired
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long TOKEN_EXPIRE_TIME = CacheConstants.EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    private final static Long TOKEN_REFRESH_THRESHOLD_MINUTES = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", TOKEN_EXPIRE_TIME);
        return rspMap;
    }

    /**
     * 为前端用户生成令牌
     *
     * @param u 前端用户对象，登录成功后传入，必须设置好用户基本信息
     * @return 包含 access_token 与 expires_in 的 Map
     */
    private SysUser toSysUser(User u) {
        SysUser s = new SysUser();
        s.setUserId(u.getId());
        s.setUserName(u.getUsername());
        s.setNickName(u.getFullName());     // 如需
        // 如需
        s.setPhonenumber(u.getPhone());     // 如需
        s.setAvatar(u.getAvatar());         // 如需
        // 其他字段按需补充
        return s;
    }
    private LoginUser wrapAsLoginUser(User u) {
        LoginUser lu = new LoginUser();
        lu.setSysUser(toSysUser(u));   // 核心：网关只关心 SysUser
        lu.setUserid(u.getId());
        lu.setUsername(u.getUsername());
        return lu;
    }
    public Map<String, Object> createUserToken(User user) {
        // 1. 生成 UUID
        String uuid = IdUtils.fastUUID();
        user.setToken(uuid);

        // 2. 封装 LoginUser
        LoginUser loginUser = wrapAsLoginUser(user);
        loginUser.setToken(uuid);
        loginUser.setIpaddr(IpUtils.getIpAddr());

        // 3. 缓存 & 过期
        refreshToken(loginUser);   // 仍然使用原来的 refreshToken(LoginUser)

        // 4. 生成 JWT
        Map<String,Object> claims = new HashMap<>();
        claims.put(SecurityConstants.USER_KEY,        uuid);
        claims.put(SecurityConstants.DETAILS_USER_ID, user.getId());
        claims.put(SecurityConstants.DETAILS_USERNAME,user.getUsername());

        String jwt = JwtUtils.createToken(claims);

        // 5. 返回
        Map<String,Object> rsp = new HashMap<>();
        rsp.put("access_token", jwt);
        rsp.put("expires_in",   TOKEN_EXPIRE_TIME);
        rsp.put("user",         user);      // 前端需要的用户信息
        return rsp;
    }


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser()
    {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token)
    {
        LoginUser user = null;
        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        }
        catch (Exception e)
        {
            log.error("获取用户信息异常'{}'", e.getMessage());
        }
        return user;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userkey = JwtUtils.getUserKey(token);
            redisService.deleteObject(getTokenKey(userkey));
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= TOKEN_REFRESH_THRESHOLD_MINUTES)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + TOKEN_EXPIRE_TIME * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, TOKEN_EXPIRE_TIME, TimeUnit.MINUTES);
    }

    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }




}
